package com.supcon.exchangedata.service;

import com.supcon.exchangedata.pojo.entity.dto.DtoInfo;
import com.supcon.exchangedata.pojo.entity.mysql.operation.rq.RqGasSupply;
import com.supcon.exchangedata.pojo.entity.mysql.operation.rq.RqLiqefedGas;
import com.supcon.exchangedata.pojo.entity.mysql.operation.rq.RqUserCount;
import com.supcon.exchangedata.pojo.entity.mysql.operation.sw.SwStatistOtherParametersMonth;
import com.supcon.exchangedata.pojo.entity.oracle.StatistOtherParametersDay;
import com.supcon.exchangedata.pojo.entity.mysql.operation.hj.GasDailyOpertionInfo;
import com.supcon.exchangedata.pojo.entity.oracle.StatistOtherParametersMonth;
import com.supcon.exchangedata.repository.master.MasterStatistOtherParametersDayRepository;
import com.supcon.exchangedata.repository.master.MasterStatistOtherParametersMonthRepository;
import com.supcon.exchangedata.repository.slave1.SlaveOneStatistOtherParametersDayRepository;
import com.supcon.exchangedata.repository.slave2.SlaveTwoGasDailyOperationInfo;
import com.supcon.exchangedata.repository.slave3.SwStatistOtherParametersMonthInfo;
import com.supcon.exchangedata.repository.slave5.RqGasSupplyInfo;
import com.supcon.exchangedata.repository.slave5.RqLiqefedGasInfo;
import com.supcon.exchangedata.repository.slave5.RqUserCountInfo;
import com.supcon.exchangedata.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yangbin
 * @Date: 2022/04/20/9:26
 * @Description:
 */
@Slf4j
@Service
public class DayGasSyncService {
    @Resource
    private SlaveTwoGasDailyOperationInfo slaveTwoGasDailyOperationInfo;
    @Resource
    private SlaveOneStatistOtherParametersDayRepository slaveOneStatistOtherParametersDayRepository;
    @Resource
    private MasterStatistOtherParametersMonthRepository monthRepository;

    @Resource
    private SwStatistOtherParametersMonthInfo swStatistOtherParametersMonthInfo;

    /**
     * type =1
     */
    @Resource
    private RqGasSupplyInfo rqGasSupplyInfo;
    /**
     * type =2
     */
    @Resource
    private RqLiqefedGasInfo rqLiqefedGasInfo;
    /**
     * type =3
     */
    @Resource
    private RqUserCountInfo rqUserCountInfo;


    @Resource
    private MasterStatistOtherParametersDayRepository dayRepository;

    @Transactional(rollbackFor = Exception.class)
    public void syncAllGasData() {
        Long objId = 3L;
        //供气量
        Long gasSupply = 30008L;
        //液化气销售量
        Long liquid = 30003L;
        //管道气供气量
        Long guandaoqi = 30027L;


        List<StatistOtherParametersDay> gasSupplyList = slaveOneStatistOtherParametersDayRepository.findAllByObjIdAndTypeAndTypeIsNotNullAndObjIdIsNotNullAndDayOfMonthKeyIsNotNullAndInAvgValueIsNotNullOrderByDayOfMonthKeyDesc(objId, gasSupply);
        List<StatistOtherParametersDay> liquidList = slaveOneStatistOtherParametersDayRepository.findAllByObjIdAndTypeAndTypeIsNotNullAndObjIdIsNotNullAndDayOfMonthKeyIsNotNullAndInAvgValueIsNotNullOrderByDayOfMonthKeyDesc(objId, liquid);
        List<StatistOtherParametersDay> guandaoqiList = slaveOneStatistOtherParametersDayRepository.findAllByObjIdAndTypeAndTypeIsNotNullAndObjIdIsNotNullAndDayOfMonthKeyIsNotNullAndInAvgValueIsNotNullOrderByDayOfMonthKeyDesc(objId, guandaoqi);
        Map<LocalDateTime, BigDecimal> mapMain = new LinkedHashMap<>();
        Map<LocalDateTime, BigDecimal> slave1 = new LinkedHashMap<>();
        Map<LocalDateTime, BigDecimal> slave2 = new LinkedHashMap<>();
        handleListToMap(mapMain, gasSupplyList);
        handleListToMap(slave1, liquidList);
        handleListToMap(slave2, guandaoqiList);
        List<GasDailyOpertionInfo> addList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        if (mapMain.size() > 0) {
            mapMain.forEach((key, value) -> {
                GasDailyOpertionInfo gasDailyOpertionInfo = new GasDailyOpertionInfo();
                gasDailyOpertionInfo.setDataTime(key);
                gasDailyOpertionInfo.setGasSupplyAmount(value);
                gasDailyOpertionInfo.setTongTime(DateTimeUtils.localDateTimeToTimeSTamp(now));
                gasDailyOpertionInfo.setBizTime(DateTimeUtils.localDateTimeToTimeSTamp(key));
                gasDailyOpertionInfo.setOp("insert");
                gasDailyOpertionInfo.setGasLiquidAmount(new BigDecimal("0"));
                gasDailyOpertionInfo.setGasPipeAmount(new BigDecimal("0"));
                if (slave1.containsKey(key)) {
                    gasDailyOpertionInfo.setGasLiquidAmount(slave1.get(key));
                }
                if (slave2.containsKey(key)) {
                    gasDailyOpertionInfo.setGasPipeAmount(slave2.get(key));
                }
                addList.add(gasDailyOpertionInfo);
            });
        }

        slaveTwoGasDailyOperationInfo.saveAll(addList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void syncNew() {
        GasDailyOpertionInfo topData = slaveTwoGasDailyOperationInfo.findTopData();
        Long objId = 3L;
        //供气量
        Long gasSupply = 30008L;
        //液化气销售量
        Long liquid = 30003L;
        //管道气供气量
        Long guandaoqi = 30027L;
        StatistOtherParametersDay topByObjIdAndType = slaveOneStatistOtherParametersDayRepository.findTopByObjIdAndTypeOrderByDayOfMonthKeyDesc(objId, gasSupply);

        LocalDateTime dayOfMonthKey = topByObjIdAndType.getDayOfMonthKey();

        LocalDateTime dataTime = topData.getDataTime();
        //新日期
        if (dayOfMonthKey.isAfter(dataTime)) {
            StatistOtherParametersDay liquidData = slaveOneStatistOtherParametersDayRepository.findDistinctByDayOfMonthKeyAndObjIdAndType(dayOfMonthKey, objId, liquid);
            StatistOtherParametersDay guandaoqiData = slaveOneStatistOtherParametersDayRepository.findDistinctByDayOfMonthKeyAndObjIdAndType(dayOfMonthKey, objId, guandaoqi);
            GasDailyOpertionInfo gasDailyOpertionInfo = new GasDailyOpertionInfo();
            gasDailyOpertionInfo.setDataTime(dayOfMonthKey);
            BigDecimal value = topByObjIdAndType.getInAvgValue() == null ? new BigDecimal("0") : new BigDecimal(topByObjIdAndType.getInAvgValue());
            gasDailyOpertionInfo.setGasSupplyAmount(value);
            Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
            gasDailyOpertionInfo.setTongTime(timestamp);
            gasDailyOpertionInfo.setBizTime(DateTimeUtils.localDateTimeToTimeSTamp(dayOfMonthKey));
            gasDailyOpertionInfo.setOp("insert");
            gasDailyOpertionInfo.setGasLiquidAmount(new BigDecimal("0"));
            gasDailyOpertionInfo.setGasPipeAmount(new BigDecimal("0"));
            if (liquidData != null && liquidData.getInAvgValue() != null) {
                gasDailyOpertionInfo.setGasLiquidAmount(new BigDecimal(liquidData.getInAvgValue()));
            }

            if (guandaoqiData != null && guandaoqiData.getInAvgValue() != null) {
                gasDailyOpertionInfo.setGasPipeAmount(new BigDecimal(guandaoqiData.getInAvgValue()));
            }
            slaveTwoGasDailyOperationInfo.save(gasDailyOpertionInfo);
        }
    }

    public void syncNewList() {
        LocalDateTime localDateTime = LocalDate.now().atStartOfDay();
        for (int i = 0; i < 7; i++) {
            LocalDateTime dateTimeTarget = localDateTime.minusDays(i);
            GasDailyOpertionInfo topData = slaveTwoGasDailyOperationInfo.findByDataTime(dateTimeTarget);
            if (topData == null) {
                Long objId = 3L;
                //供气量
                Long gasSupply = 30008L;
                //液化气销售量
                Long liquid = 30003L;
                //管道气供气量
                Long guandaoqi = 30027L;
                //新日期
                StatistOtherParametersDay topByObjIdAndType = slaveOneStatistOtherParametersDayRepository.findDistinctByDayOfMonthKeyAndObjIdAndType(dateTimeTarget, objId, gasSupply);
                StatistOtherParametersDay liquidData = slaveOneStatistOtherParametersDayRepository.findDistinctByDayOfMonthKeyAndObjIdAndType(dateTimeTarget, objId, liquid);
                StatistOtherParametersDay guandaoqiData = slaveOneStatistOtherParametersDayRepository.findDistinctByDayOfMonthKeyAndObjIdAndType(dateTimeTarget, objId, guandaoqi);

                if ((topByObjIdAndType == null || topByObjIdAndType.getInAvgValue() == null) && (liquidData == null || liquidData.getInAvgValue() == null) &&
                        (guandaoqiData == null || guandaoqiData.getInAvgValue() == null)) {
                    continue;
                }


                GasDailyOpertionInfo gasDailyOpertionInfo = new GasDailyOpertionInfo();
                gasDailyOpertionInfo.setDataTime(dateTimeTarget);
                BigDecimal value = topByObjIdAndType.getInAvgValue() == null ? new BigDecimal("0") : new BigDecimal(topByObjIdAndType.getInAvgValue());
                gasDailyOpertionInfo.setGasSupplyAmount(value);
                Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
                gasDailyOpertionInfo.setTongTime(timestamp);
                gasDailyOpertionInfo.setBizTime(DateTimeUtils.localDateTimeToTimeSTamp(dateTimeTarget));
                gasDailyOpertionInfo.setOp("insert");
                gasDailyOpertionInfo.setGasLiquidAmount(new BigDecimal("0"));
                gasDailyOpertionInfo.setGasPipeAmount(new BigDecimal("0"));
                if (liquidData != null && liquidData.getInAvgValue() != null) {
                    gasDailyOpertionInfo.setGasLiquidAmount(new BigDecimal(liquidData.getInAvgValue()));
                }

                if (guandaoqiData != null && guandaoqiData.getInAvgValue() != null) {
                    gasDailyOpertionInfo.setGasPipeAmount(new BigDecimal(guandaoqiData.getInAvgValue()));
                }
                slaveTwoGasDailyOperationInfo.save(gasDailyOpertionInfo);
            }


        }

    }

    void handleListToMap(Map<LocalDateTime, BigDecimal> map, List<StatistOtherParametersDay> lists) {
        if (!CollectionUtils.isEmpty(lists)) {
            lists.forEach((e) -> {
                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                Double inAvgValue = e.getInAvgValue();
                BigDecimal value = new BigDecimal(inAvgValue);
                map.put(dayOfMonthKey, value);
            });
        }


    }

    public Map<String, Double> handleData(List<StatistOtherParametersMonth> otherHours) {
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        HashMap<String, Double> objectObjectHashMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(otherHours)) {
            otherHours.forEach((e) -> {
                LocalDateTime collectTime = e.getLastTime();
                String key = timeFormatter.format(collectTime);
                Double inAvgValue = e.getInAvgValue();
                objectObjectHashMap.put(key, inAvgValue);

            });
        }
        return objectObjectHashMap;
    }

    public void rqNewInfoUser(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        // 设置为上一个月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();
        String format1 = format.format(date);
        RqUserCount byDay = rqUserCountInfo.findByDay(format1);
        Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
        if (byDay==null){
            StatistOtherParametersMonth one1 = monthRepository.one(30004L,format1);
            StatistOtherParametersMonth one2 = monthRepository.one(30005L,format1);
            StatistOtherParametersMonth one3 = monthRepository.one(30010L,format1);
            StatistOtherParametersMonth one4 = monthRepository.one(30028L,format1);
            StatistOtherParametersMonth one5 = monthRepository.one(30022L,format1);
            StatistOtherParametersMonth one6 = monthRepository.one(30023L,format1);
            RqUserCount userCount = new RqUserCount();
            if (null!=one1){
                userCount.setGasSupplyUser(one1.getInAvgValue());
            }
            if (null!=one2){
                userCount.setGasResidentNonUser(one2.getInAvgValue());
            }
            if (null!=one3){
                userCount.setGasResidentUser(one3.getInAvgValue());
            }
            if (null!=one4){
                userCount.setRegisteredUser19(one4.getInAvgValue());
            }
            if (null!=one5){
                userCount.setGasIntelligentMeter(one5.getInAvgValue());
            }
            if (null!=one6){
                userCount.setGasSmartMeterCoverage(one6.getInAvgValue());
            }
            userCount.setTongTime(timestamp);
            userCount.setBizTime(DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now()));
            userCount.setOp("insert");
            userCount.setDay(format1);
            userCount.setDataTime(LocalDateTime.now());
            rqUserCountInfo.save(userCount);
        }
    }

    public void rqAllInfoUser(){
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
        //查询所有数据
        List<StatistOtherParametersMonth> type30004 = monthRepository.findAllByType("30004");
        List<StatistOtherParametersMonth> type30005 = monthRepository.findAllByType("30005");
        List<StatistOtherParametersMonth> type30010 = monthRepository.findAllByType("30010");
        List<StatistOtherParametersMonth> type30028 = monthRepository.findAllByType("30028");
        List<StatistOtherParametersMonth> type30022 = monthRepository.findAllByType("30022");
        List<StatistOtherParametersMonth> type30023 = monthRepository.findAllByType("30023");

        Map<String, Double> map1 = handleData(type30004);
        Map<String, Double> map2 = handleData(type30005);
        Map<String, Double> map3 = handleData(type30010);
        Map<String, Double> map4 = handleData(type30028);
        Map<String, Double> map5 = handleData(type30022);
        Map<String, Double> map6 = handleData(type30023);

        List<RqUserCount> objects = new ArrayList<>();

        type30004.forEach(v->{
            RqUserCount userCount = new RqUserCount();
            LocalDateTime lastTime = v.getLastTime();
            String key = timeFormatter.format(lastTime);
            if (map1.containsKey(key)){
                userCount.setGasSupplyUser(map1.get(key));
            }
            if (map2.containsKey(key)){
                userCount.setGasResidentNonUser(map2.get(key));
            }
            if (map3.containsKey(key)){
                userCount.setGasResidentUser(map3.get(key));
            }
            if (map4.containsKey(key)){
                userCount.setRegisteredUser19(map4.get(key));
            }
            if (map5.containsKey(key)){
                userCount.setGasIntelligentMeter(map5.get(key));
            }
            if (map6.containsKey(key)){
                userCount.setGasSmartMeterCoverage(map6.get(key));
            }
            userCount.setTongTime(timestamp);
            userCount.setBizTime(DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now()));
            userCount.setOp("insert");
            userCount.setDay(v.getMonthKey());
            userCount.setDataTime(lastTime);
            objects.add(userCount);
        });
        this.rqUserCountInfo.saveAll(objects);

    }

    public void rqInfo(String type){
        Calendar instance = Calendar.getInstance();
        Date time = instance.getTime();
        SimpleDateFormat simpleDateFormats = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormats.format(time);
        String years = Years(format);
        Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
        //插入前先查询前置库是否存在当月数据
        if (type =="1"){
            List<RqGasSupply> all = rqGasSupplyInfo.findAll();
            if (CollectionUtils.isEmpty(all)){
                List<DtoInfo> list = list("30008");
                list.forEach(s->{
                    RqGasSupply rqGasSupply = new RqGasSupply();
                    BeanUtils.copyProperties(s,rqGasSupply);
                    all.add(rqGasSupply);
                });
                this.rqGasSupplyInfo.saveAll(all);
            }else {
                RqGasSupply byTime = rqGasSupplyInfo.findByTime(years);
                if (null == byTime){
                    StatistOtherParametersMonth key = monthRepository.findByObjIdAndTypeAndMonthKey(3L, 30008L, years);
                    RqGasSupply rqGasSupply = new RqGasSupply();
                    rqGasSupply.setTongTime(timestamp);
                    rqGasSupply.setBizTime(new Date());
                    rqGasSupply.setOp("insert");
                    rqGasSupply.setAvgValue(key.getInAvgValue().toString());
                    rqGasSupply.setMonthKey(years);
                    rqGasSupplyInfo.save(rqGasSupply);
                }
            }
        }else if (type =="2"){
            List<RqLiqefedGas> all = rqLiqefedGasInfo.findAll();
            if (CollectionUtils.isEmpty(all)){
                List<DtoInfo> list = list("30003");
                list.forEach(s->{
                    RqLiqefedGas rqLiqefedGas = new RqLiqefedGas();
                    BeanUtils.copyProperties(s,rqLiqefedGas);
                    all.add(rqLiqefedGas);
                });
                this.rqLiqefedGasInfo.saveAll(all);
            }else {
                RqLiqefedGas byTime = rqLiqefedGasInfo.findByTime(years);
                if (null == byTime){
                    StatistOtherParametersMonth key = monthRepository.findByObjIdAndTypeAndMonthKey(3L, 30003L, years);
                    RqLiqefedGas rqLiqefedGas = new RqLiqefedGas();
                    rqLiqefedGas.setTongTime(timestamp);
                    rqLiqefedGas.setBizTime(new Date());
                    rqLiqefedGas.setOp("insert");
                    rqLiqefedGas.setAvgValue(key.getInAvgValue().toString());
                    rqLiqefedGas.setMonthKey(years);
                    rqLiqefedGasInfo.save(rqLiqefedGas);
                }
            }
        }else if (type =="3"){
            List<RqUserCount> all = rqUserCountInfo.findAll();
            if (CollectionUtils.isEmpty(all)){
                List<DtoInfo> list = list("30004");
                list.forEach(s->{
                    RqUserCount rqUserCount = new RqUserCount();
                    BeanUtils.copyProperties(s,rqUserCount);
                    all.add(rqUserCount);
                });
                this.rqUserCountInfo.saveAll(all);
            }else {
                RqUserCount  byTime = rqUserCountInfo.findByTime(years);
                if (null == byTime) {
                    //已存在数据 只需要获取当月的数据进行操作 获取当月我们自己的数据
                    StatistOtherParametersMonth key = monthRepository.findByObjIdAndTypeAndMonthKey(3L, 30004L, years);
                    RqUserCount sw1 = new RqUserCount();
                    sw1.setTongTime(timestamp);
                    sw1.setBizTime(new Date());
                    sw1.setOp("insert");
                    sw1.setGasSupplyUser(key.getInAvgValue());
                    rqUserCountInfo.save(sw1);
                }
            }
        }
    }


    public static String Years(String date) {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date parse = null;
        try {
            parse = formats.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String format1 = format.format(parse);
        return format1;
    }


    public List<DtoInfo> list(String types){
        Calendar instance = Calendar.getInstance();
        Date time = instance.getTime();
        SimpleDateFormat simpleDateFormats = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormats.format(time);
        String years = Years(format);
        List<DtoInfo> objects = new ArrayList<>();
        Timestamp timestamp = DateTimeUtils.localDateTimeToTimeSTamp(LocalDateTime.now());
        List<StatistOtherParametersMonth> type = monthRepository.findAllByType(types);
        type.stream().forEach(s -> {
            DtoInfo dtoInfo = new DtoInfo();
            dtoInfo.setTongTime(timestamp);
            dtoInfo.setBizTime(new Date());
            dtoInfo.setOp("insert");
            if (s.getInAvgValue() != null) {
                dtoInfo.setAvgValue(s.getInAvgValue().toString());
            }
            dtoInfo.setMonthKey(years);
            objects.add(dtoInfo);
        });
        return objects;
    }
}
